﻿#include "Country.h"
#include "DatabaseMgmt.h"

CCountry::CCountry()
{

}

CCountry::~CCountry()
{

}

int CCountry::insertRow(QString name, QString code)
{
	int ret = 0;

	QString strSql = QString("INSERT INTO TB_COUNTRIES (NAME, CODE) VALUES ('%1','%2')")
		.arg(name)
		.arg(code);

	QSqlQuery query;
	CDatabaseMgmt::getInstance()->execSql(strSql, query);

	if (query.lastError().type() != QSqlError::NoError)
	{
		ret = CONST_ERR_EXEC_SQL_FAILED;
	}

	return ret;
}

int CCountry::removeRow(int id)
{
	int ret = 0;

	QString strSql = QString("DELETE FROM TB_COUNTRIES WHERE UID=%1")
		.arg(id);

	QSqlQuery query;
	CDatabaseMgmt::getInstance()->execSql(strSql, query);

	if (query.lastError().type() != QSqlError::NoError)
	{
		ret = CONST_ERR_EXEC_SQL_FAILED;
	}

	return ret;
}

int CCountry::modifyRow(int id, QString name, QString code)
{
	int ret = 0;

	QString strSql = QString("UPDATE TB_COUNTRIES SET NAME='%1' CODE='%2' WHERE UID=%3")
		.arg(name)
		.arg(code)
		.arg(id);

	QSqlQuery query;
	CDatabaseMgmt::getInstance()->execSql(strSql, query);

	if (query.lastError().type() != QSqlError::NoError)
	{
		ret = CONST_ERR_EXEC_SQL_FAILED;
	}

	return ret;
}

int CCountry::queryAll(QVector<CountryInfo>& countries)
{
	int ret = 0;

	QString strSql = QString("SELECT UID, NAME, CODE FROM TB_COUNTRIES");

	QSqlQuery query;
	CDatabaseMgmt::getInstance()->execSql(strSql, query);

	if (query.lastError().type() != QSqlError::NoError)
	{
		ret = CONST_ERR_EXEC_SQL_FAILED;
	}
	else
	{
		while (query.next())
		{
			CountryInfo country;

			country.uid = query.value("UID").toUInt();
			country.name = query.value("NAME").toString();
			country.code = query.value("CODE").toString();

			countries.append(country);
		}

	}
	return ret;
}
